package com.fjl.lock;

import java.util.concurrent.locks.ReentrantLock;

public class InterruptDemo {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        // 主线程先获取锁，确保后续线程无法立即获得锁
        lock.lock();
        System.out.println("Main thread acquired the lock.");

        Thread t = new Thread(() -> {
            try {
                System.out.println("Child thread attempting to acquire the lock interruptibly.");
                // 使用 lockInterruptibly() 方法，当线程等待过程中被中断会抛出 InterruptedException
                lock.lockInterruptibly();
                try {
                    System.out.println("Child thread acquired the lock.");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                System.out.println("Child thread was interrupted while waiting for the lock.");
            }
        });

        t.start();

        // 等待一段时间，确保子线程进入等待队列
        Thread.sleep(1000);

        System.out.println("Main thread interrupting child thread.");
        // 中断等待获取锁的子线程，模拟中断情况
        t.interrupt();

        // 为了让子线程顺利结束，主线程释放锁
        lock.unlock();
    }
}
